﻿using RpcHelper;
using Wedonek.RpcStore.Gateway.Interface;
using Wedonek.RpcStore.Gateway.Model;
using Wedonek.RpcStore.Service.Interface;
using Wedonek.RpcStore.Service.Model;

namespace Wedonek.RpcStore.Gateway.Service
{
        internal class DictateNodeService : IDictateNodeService
        {
                private readonly IDictateNodeCollect _Dictate;

                public DictateNodeService (IDictateNodeCollect dictate)
                {
                        this._Dictate = dictate;
                }
                public long Add (DictateNewNode add)
                {
                        if (add.ParentId != 0)
                        {
                                DictateNode node = this._Dictate.Get (add.ParentId);
                                if (node.IsEndpoint)
                                {
                                        throw new ErrorException ("rpc.dictate.node.no.allow.add");
                                }
                        }
                        return this._Dictate.Add (add);
                }
                public TreeNode[] GetTrees ()
                {
                        DictateNode[] nodes = this._Dictate.Gets ();
                        return nodes.Convert (a => a.ParentId == 0, a => new TreeNode
                        {
                                Id = a.Id,
                                Name = a.DictateName,
                                Children = this._GetTrees (a, nodes)
                        });
                }
                private TreeNode[] _GetTrees (DictateNode node, DictateNode[] list)
                {
                        return list.Convert (a => a.ParentId == node.Id, a => new TreeNode
                        {
                                Id = a.Id,
                                Name = a.DictateName,
                                Children = this._GetTrees (a, list)
                        });
                }
                public void Drop (long id)
                {
                        DictateNode node = this._Dictate.Get (id);
                        this._Dictate.Drop (node);
                }

                public DictateNode Get (long id)
                {
                        return this._Dictate.Get (id);
                }

                public DictateNode[] Gets ()
                {
                        return this._Dictate.Gets ();
                }

                public DictateNode[] Gets (long parentId)
                {
                        return this._Dictate.Gets (parentId);
                }

                public void Set (long id, string name)
                {
                        DictateNode node = this._Dictate.Get (id);
                        this._Dictate.Set (node, name);
                }
        }
}
